package com.qingke.easyjava.springhibernate.servlet;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.qingke.easyjava.springhibernate.bean.Expense;
import com.qingke.easyjava.springhibernate.service.ExpenseService;

public class ListExpenseServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        WebApplicationContext wac = WebApplicationContextUtils
                .getRequiredWebApplicationContext(getServletContext());
        ExpenseService service = wac.getBean(ExpenseService.class);

        List<Expense> results = service.listExpense();
        StringBuilder sb = new StringBuilder();
        
        for (Expense exp : results) {
            sb.append(exp.toString()).append("\n");
        }
        
        OutputStream os = resp.getOutputStream();
        os.write(sb.toString().getBytes());
        os.flush();
        os.close();
    }
}
